const { Controller } = require('varal');

class RegionController extends Controller {
	async index() {
		const { page = 1, page_size = 20, name } = this.app.fields;

		const serv = this.app.service('RegionService');

		return serv.get({ name }, page, page_size).then(({ data, total }) => {
			this.app.json({
				err_code: 0,
				data: {
					data,
					total
				}
			})
		})
	}

	async save() {
		const serv = this.app.service('RegionService');

		return serv.save(this.app.fields).then(() => {
			this.app.json({
				err_code: 0
			})
		}).catch(err => {
			this.app.json({
				err_code: 1,
				err_msg: err.toString()
			})
		})
	}

	async cascader() {
		const { parent_id = 0 } = this.app.fields;

		const serv = this.app.service('RegionService');
		return serv.cascader(parent_id).then((data) => {
			this.app.json({
				err_code: 0,
				data
			})
		}).catch((err) => {
			this.app.json({
				err_code: 1,
				err_msg: err.toString()
			})
		})
	}

	async delete() {
		const serv = this.app.service('RegionService');

		const { id } = this.app.fields;
		return serv.delete(id).then(() => {
			this.app.json({
				err_code: 0
			})
		})
	}
}

exports = module.exports = RegionController;
